//
//  MinedoPosVC.m
//  NewPro
//
//  Created by 何荧红 on 2019/2/23.
//  Copyright © 2019 何荧红. All rights reserved.
//

#import "MinedoPosVC.h"
#import "ScanQRViewController.h"
#import "BusinessShopflv.h"
#import "addAdressCell.h"
#import "MineShareVC.h"
#import "MinedoPosStore.h"

@interface MinedoPosVC ()<UITableViewDelegate,UITableViewDataSource,ScanQRViewControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) BusinessShopflv *ShopflvView;

@property (nonatomic, strong) UIButton *sure;

@property (nonatomic, copy) NSString *merchantName;
@property (nonatomic, copy) NSString *phoneName;
@property (nonatomic, copy) NSString *code;
@property (nonatomic, copy) NSString *realCode;
@property (nonatomic, copy) NSString *posNnstanceSn;
@property (nonatomic, copy) NSString *shopflv;

@property (nonatomic, copy) NSString *SQimg;
@property (nonatomic, copy) NSString *shareurl;

@end

@implementation MinedoPosVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCSS];
    [self ViewWithShopflv];
    [self getNoml];
    [self getWithlevelData];
}
- (void)initCSS{
    ViewHeader *header = [[ViewHeader alloc]initWithDefaultString:@"自助报单"];
    [self.view addSubview:header];
    self.sure = [[UIButton alloc]init];
    [_sure addTarget:self action:@selector(toNextVC) forControlEvents:UIControlEventTouchUpInside];
    _sure.backgroundColor = [UIColor colorWithHexString:@"0CA6F0"];
    _sure.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:18];
    [_sure setTitle:@"下一步" forState:UIControlStateNormal];
    [_sure setTitleColor:[UIColor colorWithHexString:@"ffffff"] forState:UIControlStateNormal];
    [self.view addSubview:_sure];
    [_sure mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(-iPhoneX_Bottom);
        make.left.equalTo(self.view.mas_left);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(49);
    }];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"addAdressCell" bundle:nil] forCellReuseIdentifier:@"addAdressCellID"];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(header.mas_bottom);
        make.bottom.equalTo(self.sure.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
    }];
}
- (void)getNoml{
    [[[MinedoPosStore alloc]init] GetNomlWithCustomId:[UserDefaultsManager sharedInstance].user_id Success:^(NSDictionary * _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            self.SQimg = res[@"data"][@"items"][@"organizationQrCode"];
            self.shareurl = res[@"data"][@"items"][@"organizationUrl"];
        }else{
            [self showMBPError:res[@"msg"]];
        }
    } Failure:^(NSError * _Nonnull error) {
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (void)getSQimg{
    [[[MinedoPosStore alloc]init] GetNomlWithCustomId:[UserDefaultsManager sharedInstance].user_id andRate:[self.shopflv substringToIndex:self.shopflv.length - 1] Success:^(NSDictionary * _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            self.SQimg = res[@"data"][@"items"][@"organizationQrCode"];
            self.shareurl = res[@"data"][@"items"][@"organizationUrl"];
        }else{
            [self showMBPError:res[@"msg"]];
        }
    } Failure:^(NSError * _Nonnull error) {
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (void)ViewWithShopflv{
    WS(weakself)
    self.ShopflvView = [[BusinessShopflv alloc]init];
    [self.ShopflvView setGetWithFlvBlock:^(NSString * substring) {
        weakself.shopflv = substring;
        [weakself getSQimg];
        [weakself.tableView reloadData];
    }];
    [self.view addSubview:self.ShopflvView];
}
- (void)toNextVC{
    self.sure.enabled = NO;
    NSMutableDictionary *prams = [[NSMutableDictionary alloc]init];
    [prams setObject:[UserDefaultsManager sharedInstance].user_id forKey:@"customId"];
    if (self.merchantName) {
        [prams setObject:self.merchantName forKey:@"merchantName"];
    if (self.phoneName) {
        [prams setObject:self.phoneName forKey:@"phone"];
    if (self.code) {
    if ([self.code isEqualToString:self.realCode]) {
    if (self.posNnstanceSn) {
        [prams setObject:self.posNnstanceSn forKey:@"sn"];
    if (!self.shopflv) {
        self.shopflv = @"0.60";
    }
        [prams setObject:[self.shopflv substringToIndex:self.shopflv.length - 1] forKey:@"rate"];
        [self loadData:prams];
    }else{
        [self showMBPError:@"输入机器序列号(SN)"];
    }
    }else{
        [self showMBPError:@"请输入正确的验证码"];
    }
    }else{
        [self showMBPError:@"请输入验证码"];
    }
    }else{
        [self showMBPError:@"请输入手机号码"];
    }
    }else{
        [self showMBPError:@"请输入商户姓名"];
    }
}
- (void)loadData:(NSDictionary *)prams{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[[MinedoPosStore alloc]init] PostAddSimplePOSWithPrams:prams Success:^(NSDictionary * _Nonnull res) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([res[@"msg"] isEqualToString:@"success"]) {
            MineShareVC *VC = [[MineShareVC alloc] init];
            VC.dic = @{@"merchantName":self.merchantName,@"phone":self.phoneName,@"rate":self.shopflv,@"sn":self.posNnstanceSn,@"SQimg":self.SQimg,@"url":self.shareurl};
            [[AppDelegate sharedAppDelegate] pushViewController:VC];
        }else{
            self.sure.enabled = YES;
            [self showMBPError:res[@"msg"]];
        }
    } Failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        self.sure.enabled = YES;
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
#pragma mark - scan QR code delegate
- (void)didScanSuccessWithResult:(NSString *)result {
    // 先将服务端返回的 URL 转义
    NSString *decodedString = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.posNnstanceSn = decodedString;
    [self.tableView reloadData];
}
- (void)getWithlevelData{
    [[[MinedoPosStore alloc]init] GetLevelWithPrams:@{@"customId":[UserDefaultsManager sharedInstance].user_id,@"isNew":@"1"} Success:^(NSDictionary * _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            self.ShopflvView.levelstr = res[@"data"][@"levelAmount"];
        }else{
            [self showMBPError:res[@"msg"]];
        }
    } Failure:^(NSError * _Nonnull error) {
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (void)sendCodeWith:(NSIndexPath *)index{
    [[[MinedoPosStore alloc]init] sendCodeWithTelephoneNumber:self.phoneName Success:^(NSDictionary * _Nonnull res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            self.realCode = res[@"data"][@"code"];
            addAdressCell *Cell = [self.tableView cellForRowAtIndexPath:index];
            [Cell daojishi];
        }else{
            [self showMBPError:res[@"msg"]];
        }
    } Failure:^(NSError * _Nonnull error) {
        [self showMBPError:[HttpTool handleError:error]];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 3;
    }else{
        return 2;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 10;
    }
    return 0.01f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    addAdressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addAdressCellID"];
    cell.rightarrow.hidden = YES;
    cell.sendbutton.hidden = YES;
    cell.detailtext.enabled = YES;
    cell.detailtext.textColor = [UIColor colorWithHexString:@"333333"];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.subtitle.text = @"商户姓名";
            if (self.merchantName) {
                if (self.merchantName.length > 0) {
                    cell.detailtext.text = self.merchantName;
                }else{
                    cell.detailtext.placeholder = @"请输入商户姓名";
                }
            }else{
                cell.detailtext.placeholder = @"请输入商户姓名";
            }
        }else if (indexPath.row == 1) {
            cell.subtitle.text = @"商户电话";
            if (self.phoneName) {
                if (self.phoneName.length > 0) {
                    cell.detailtext.text = self.phoneName;
                }else{
                    cell.detailtext.placeholder = @"输入手机号码";
                }
            }else{
                cell.detailtext.placeholder = @"输入手机号码";
            }
        }else if (indexPath.row == 2) {
            cell.subtitle.text = @"验证码";
            if (self.code) {
                if (self.code.length > 0) {
                    cell.detailtext.text = self.code;
                }else{
                    cell.detailtext.placeholder = @"输入验证码";
                }
            }else{
                cell.detailtext.placeholder = @"输入验证码";
            }
            cell.sendbutton.hidden = NO;
            [cell.sendbutton setTitle:@"获取验证码" forState:UIControlStateNormal];
            [cell setSendBlock:^{
                if ([self.phoneName isVaildMobileNo]) {
                    [self sendCodeWith:indexPath];
                }else{
                    [self showMBPError:@"请输入正确的手机号"];
                }
            }];
        }
        [cell setDetailBlock:^(NSString * _Nonnull str) {
            if (indexPath.row == 0) {
                self.merchantName = str;
            }else if (indexPath.row == 1) {
                self.phoneName = str;
            }else if (indexPath.row == 2) {
                self.code = str;
            }
        }];
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            cell.subtitle.text = @"机具编号";
            if (self.posNnstanceSn) {
                if (self.posNnstanceSn.length > 0) {
                    cell.detailtext.text = self.posNnstanceSn;
                }else{
                    cell.detailtext.placeholder = @"输入机器序列号(SN)";
                }
            }else{
                cell.detailtext.placeholder = @"输入机器序列号(SN)";
            }
            cell.sendbutton.hidden = NO;
            [cell.sendbutton setTitle:@"自动识别" forState:UIControlStateNormal];
        }else if (indexPath.row == 1) {
            cell.subtitle.text = @"商户费率";
            cell.detailtext.enabled = NO;
            if (self.shopflv) {
                if (self.shopflv.length > 0) {
                    cell.detailtext.text = self.shopflv;
                }else{
                    cell.detailtext.text = @"0.60%";
                }
            }else{
                cell.detailtext.text = @"0.60%";
            }
        }
        [cell setDetailBlock:^(NSString * _Nonnull str) {
            if (indexPath.row == 0) {
                self.posNnstanceSn = str;
            }
        }];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        if (indexPath.row == 1) {
            [self.ShopflvView ViewDidPush];
        }
    }
}

@end
